export  function createBlobUrl(base64AudioData:string){
    let byteArrays = []
    let byteString = atob(base64AudioData)//将base64格式的字符串转为utf-8格式的字符串

    for (let i = 0; i < byteString.length; i++) {
        byteArrays.push(byteString.charCodeAt(i))//将每个字符串转为utf-16编码的值
    }
    let audioBuffer = new Uint8Array(byteArrays)
    let blob = new Blob([audioBuffer], { type: 'audio/mp3' })
    let blobUrl = URL.createObjectURL(blob)
    return blobUrl
}
export async function generateAudio(text:string){
    const token=import.meta.env.VITE_ACCESS_TOKEN
    const appId=import.meta.env.VITE_APP_ID
    const voiceName='zh_female_daimengchuanmei_moon_bigtts'
    const endpoint='/tts/api/v1/tts'
    const headers={
        'Authorization': `Bearer;${token}`,
        'Content-Type': 'application/json'
    }
    const payload=
    {
      user: {
        uid: 'sbd'
      },
      audio: {
        voice_type: voiceName,
        encoding: 'ogg_opus',
        speed_ratio: 1.0,
        emotion: 'happy',
      },
      request: {
        reqid: Math.random().toString(36).substring(7),
        text: text,
        text_type: 'plain',
        operation: 'query'
      },
      app: {
        appid: appId,
        token,
        cluster: 'volcano_tts',

      }
    }
    const res=await fetch(endpoint,{
        method:'POST',
        headers,
        body:JSON.stringify(payload)
    })
    const data=await res.json()
    if(!data.data){
        throw new Error('生成音频失败')
    }
    return createBlobUrl(data.data)

}
